package com.wxy.favorites.util;

import com.wxy.favorites.constant.PublicConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

@Component
@Slf4j
public class EmailUtils {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String systemMail;

    /**
     * 异步发送文本邮件
     *
     * @param mailTo
     * @param mailHead
     * @param mailContent
     */
    @Async
    public void sendSimpleMail(String mailTo, String mailHead, String mailContent) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(systemMail);
            message.setTo(mailTo.split(PublicConstants.DEFAULT_DELIMITER));
            message.setSubject(mailHead);
            message.setText(mailContent);
            javaMailSender.send(message);
        } catch (Exception e) {
            log.error("发送邮件失败：mailTo = {}, mailHead = {}, mailContent = {}", mailTo, mailHead, mailContent);
        }
    }

    /**
     * 异步发送html邮件
     *
     * @param mailTo
     * @param mailHead
     * @param mailContent
     */
    @Async
    public void sendHtmlMail(String mailTo, String mailHead, String mailContent) {
        try {
            MimeMessage mimeMailMessage = this.javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMailMessage, true, "utf-8");
            messageHelper.setFrom(systemMail);
            messageHelper.setTo(mailTo.split(PublicConstants.DEFAULT_DELIMITER));
            messageHelper.setSubject(mailHead);
            messageHelper.setText(mailContent, true);
            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            log.error("发送邮件失败：mailTo = {}, mailHead = {}, mailContent = {}", mailTo, mailHead, mailContent);
        }
    }
}
